﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WURFL;
using WURFL.Config;

using Nucleo.Wurfl.Creator;
using Nucleo.Wurfl.Simulation;
using Nucleo.Wurfl.Storage;


namespace Nucleo.Wurfl
{
	public class WurflDeviceManager
	{
		public const String WurflManagerCacheKey = "__WurflManager";
		public const String WurflDataFilePath = "~/App_Data/wurfl-latest.zip";
		public const String WurflPatchFilePath = "~/App_Data/web_browsers_patch.xml";

		private static IWurflCreator _creator = null;
		private static IWurflSimulator _simulator = null;
		private static IWurflStore _store = null;



		public static IWurflCreator Creator
		{
			get { return _creator; }
			set
			{
				if (_creator == value)
					return;

				lock (typeof(IWurflCreator))
				{
					if (_creator == value)
						return;

					_creator = value;
				}
			}
		}

		public static IWurflSimulator Simulator
		{
			get { return _simulator; }
			set
			{
				if (_simulator == value)
					return;

				lock (typeof(IWurflSimulator))
				{
					if (_simulator == value)
						return;

					_simulator = value;
				}
			}
		}

		public static IWurflStore Store
		{
			get { return _store; }
			set
			{
				if (_store == value)
					return;

				lock (typeof(IWurflStore))
				{
					if (_store == value)
						return;

					_store = value;
				}
			}
		}



		private static IWURFLManager CreateManager()
		{
			return Creator.CreateManager();
		}

		public static IWURFLManager GetManager()
		{
			var store = Store;
			var wurflManager = (store != null) ? store.GetManager() : null;

			if (wurflManager == null)
			{
				wurflManager = CreateManager();

				if (store != null)
					store.SaveManager(wurflManager);
			}

			return wurflManager;
		}
	}
}
